package require tclodbc
package provide ::wt::database::clients::tclOdbcFactory 1

namespace eval ::wt::database::clients::tclOdbcFactory:: {
  variable dataSources
  variable databases
}

# Register a data source ID. The createScript parameter is a script that
# creates the database connection. Example:
#
#     registerDataSource employeeDb \
#       {database db "DRIVER=Microsoft Paradox Driver (*.db);DBQ=C:\\db"}
#
# When subsequent code tries to open that dataSourceId, an existing
# connection will be returned, or the creation script will be evaluated.

proc ::wt::database::clients::tclOdbcFactory::registerDataSource {dataSourceId createScript} {
  variable dataSources
  set dataSources($dataSourceId) $createScript
}

# Get an existing connection or create a new one

proc ::wt::database::clients::tclOdbcFactory::open {dataSourceId} {
  variable databases
  if {[info exists databases($dataSourceId)]} {
    return $databases($dataSourceId)
  } else {
    variable dataSources
    if {![info exists dataSources($dataSourceId)]} {
      error "Unknown data source ID: \"$dataSourceId\". Unable to open database connection."
    } else {
      set createScript $dataSources($dataSourceId)
      set db [eval $createScript]
      if {$db == ""} {
        error "Failed to open data source \"$dataSourceId\". Connection script: \"$dataSource\"."
      }
      return $db
    }
  }
}

# Close the connection

proc ::wt::database::clients::tclOdbcFactory::close {dataSourceId} {
  variable databases
  if {[info exists databases($dataSourceId)]} {
    set db $databases($dataSourceId)
    $db disconnect
  }
}
